define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'centralcontact/index' + location.search,
                    add_url: 'centralcontact/add',
                    edit_url: 'centralcontact/edit',
                    del_url: 'centralcontact/del',
                    multi_url: 'centralcontact/multi',
                    table: 'centralcontact',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                //search:false,
                showToggle:false,
                showExport:false,
                undefinedText:'',
                showColumns: false,
                // detailView: true,
                rowStyle:function(row,index){
                    var style = {};

                    if(row.is_remind == 1 )
                        style={css:{'color':'#ff0000'}};
                    return style;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: '', title: __('序号'), table: table,formatter: Table.api.formatter.natureorder, operate: false},

                        {field: 'name', title: __('Name'),width: "100px",operate: 'like'},
                        {field: 'investment_total', title: '总投资(亿)', width: "70px",operate:'BETWEEN',
                            // formatter:function(value,row,index) {
                            //     // console.log(value);
                            //     if (typeof value == "object" ) {
                            //         return '';
                            //     } else {
                            //         return value;
                            //     }
                            // }
                            formatter:function(value,row,index) {
                                if(value == -100)
                                    return '待定';
                                else if(value > 0)
                                    return parseFloat(value);
                                else
                                    return '';
                            }
                    
                        },

                        {field: 'summary', title: __('项目简介'),operate:false,formatter: function(value,row,index) {
                            var str = value?value:'';
                            return '<div title="'+str+'" style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+str+'</div>';
                        }},
                        {field: 'progression', title: __('进展情况'),operate:false,formatter: function(value,row,index) {
                                var str = value?value:'';
                                return '<div title="'+str+'" style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+str+'</div>';
                            }},
                        {field: 'state', title: __('当前阶段'),width:'60px',

                            searchList: $.getJSON("selectlist/state")

                        },
                        {field: 'next_measure', title: __('下一步措施'),operate:false,formatter: function(value,row,index) {
                                var str = value?value:'';
                                return '<div title="'+str+'" style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+str+'</div>';
                            }},
                        {field: 'problem', title: __('存在问题'),operate:false,formatter: function(value,row,index) {
                                var str = value?value:'';
                                return '<div title="'+str+'" style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+str+'</div>';
                            }},
                        {field: 'access_time_text', title: "计划准入时间",width: "100px",operate:false,},
                        {field: 'sign_time_text', title: __('计划签约时间'),width: "100px",operate:false,},
                        {field: 'investment_area', title: __('投资方地区'),width: "100px",operate: 'like'},
                        // {field: 'register_time_text', title: __('注册时间')},
                        {field: 'chargedep_names', title: __('责任单位'),width:'120px',operate: 'like'},
                        {field: 'settle_street_names', title: __('落户街道'),width: "100px",operate: 'like'},
                        // {field: 'receive_time_text', title: __('接洽时间'),width: "100px"},
                        {field: 'receive_time',
                            title: __('接洽时间'),
                            width: "100px",
                            operate:'RANGE',
                            addclass:'datetimerange',
                            formatter: Table.api.formatter.datetimedate
                        },
                        {field: 'leader_ids', title: "参与区领导",width: "100px",visible:false,
                            operate: 'FIND_IN_SET',
                            searchList: $.getJSON("selectlist/index/tablename/leader")},

                        {field: 'centraloffice_name', title: __('责任科室'),width:'120px',operate: 'like'},
                        {field: 'contact_name', title: __('科室责任人'),width: "100px",operate: 'like'},
                        // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate},
                        // {field: 'id', title: __('Id')},
                        {field: 'status',title:'状态',operate:false,
                            formatter: function (value,row,index) {
                                if(value == 0) {
                                    return '<a href="javascript:;" class="btn btn-success btn-xs ">已审核</a>';
                                }else if(value == '100')
                                {
                                    return '<a href="centralcontact/checkedit/ids/' + row.id + '" class="btn btn-danger   btn-addtabs btn-xs" title="审核">待审核</a>';
                                }else if(value == '200'){
                                    return '<a href="javascript:;" data-info="'+row.reject_reason+'" class="btn btn-warning btn-xs btn-rejectinfo">已驳回</a>';
                                }else if(value == '300'){
                                    return '<a href="javascript:;" class="btn btn-info btn-edit btn-xs">待提交</a>';
                                }

                            }
                        },
                    ]
                ],
                // onExpandRow: function(index, row, $detail) {
                //     console.log(row);
                //     InitSubTable(index, row, $detail);
                // }
            });

            InitSubTable = function(index, row, $detail) {
                var html = '';
                html += '<table class="table table-striped table-bordered " style="width:100%" >';
                // html += '<tr>';
                // html += '<th  style="text-align:center">序号</th>'
                // html += '<th  style="text-align:center">拜访企业</th>'
                // html += '<th  style="text-align:center">项目内容</th>'
                // html += '<th  style="text-align:center">责任单位</th>'
                // html += '<th  style="text-align:center">工作进展情况</th>'
                // html += '<th  style="text-align:center">存在问题</th>'
                // html += '<th  style="text-align:center">下步计划</th>'
                // html += '<th  style="text-align:center">操作</th>'
                // html += '</tr>';
                // var numArr = Controller.api.mergeCells(row.contents,'company');
                for(var i=0;i<row.progress.length;i++) {
                    var item = row.progress[i];
                    // console.log(value.company)
                    // console.log(numArr)
                    html += '<tr data-index='+i+' >';
                    // let it = numArr.find((v)=>{
                    //     return v.index == i
                    // })

                    html += '<td>' + (i+1) + '</td>'
                    // if(it)
                        html += '<td >' + item.content + '</td>'
                    // html += '<td>' + Controller.api.formattercontent(item.project_summary) + '</td>'
                    // html += '<td>' + item.chargedep_names + '</td>'
                    // html += '<td>' + Controller.api.formattercontent(item.project_progress) + '</td>'
                    // html += '<td>' + Controller.api.formattercontent(item.project_problem) + '</td>'
                    // html += '<td>' + Controller.api.formattercontent(item.project_nextplan) + '</td>'
                    // html += '<td>'
                    html += '<a href="leader_approach/editcontent/ids/' + item.id + '" class="btn btn-xs btn-success btn-dialog" data-toggle="tooltip" title=""  data-original-title="编辑"><i class="fa fa-pencil"></i></a>'
                    // html += ' <a href="javascript:;" class="btn btn-xs btn-danger btn-delone" data-toggle="tooltip" title="" data-table-id="table" data-field-index="6" data-row-index="0" data-button-index="2" data-original-title="删除"><i class="fa fa-trash"></i></a>'
                    html += '</td>';
                    html += '</tr>';
                };
                html += '</table>';

                $detail.html(html)

            }

            $("#table").on("click",'.btn-rejectinfo',function (table){
                Layer.open({
                    type: 1,
                    title: __('查看驳回原因'),
                    area: ["500px", "400px"],
                    content: $(this).data('info'),
                    success: function (layero) {
                        Form.api.bindevent($("#resetpwd-form", layero), function (data) {
                            Layer.closeAll();
                        });
                    }
                });
            })


            // 为表格绑定事件
            Table.api.bindevent(table);

            $(".btn-passall").click(function (){

                Layer.confirm(__('确定要通过所有吗?'), {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: "centralcontact/passall" ,
                        success: function (ret) {
                            Layer.alert(ret.msg, function(index){
                                Layer.closeAll();
                            });
                        },
                        error : function(error) {
                            console.log(error);
                        }
                    });
                    Layer.closeAll();
                });
            });

            $("#btn-import-custom").click(function () {
                var url = 'centralcontact/import';
                Fast.api.open(url, __('Import'), {});
            });


            var parenttable = table.closest('.bootstrap-table');
            var options = table.bootstrapTable('getOptions');
            var toolbar = $(options.toolbar, parenttable);
            $(toolbar).on('click', ".btn-detail", function () {
                var that = this;
                //循环弹出多个编辑框
                $.each(table.bootstrapTable('getSelections'), function (index, row) {
                    var url = 'centralcontact/detail';
                    row = $.extend({}, row ? row : {}, {ids: row[options.pk]});
                    var url = Table.api.replaceurl(url, row, table);
                    var icon = 'fa fa-info';
                    Backend.api.addtabs(url, '详情-'+row.receive_time_text, icon);
                    // Fast.api.open(url, __('详情'), $(that).data() || {});
                });
            });

            $(toolbar).on('click', "#btn-progress", function () {
                var that = this;
                //循环弹出多个编辑框
                $.each(table.bootstrapTable('getSelections'), function (index, row) {
                    var url = 'centralcontact/addprogress';
                    row = $.extend({}, row ? row : {}, {ids: row[options.pk]});
                    var url = Table.api.replaceurl(url, row, table);
                    var icon = 'fa fa-info';
                    Fast.api.open(url, __('新增进展'), $(that).data() || {});
                });
            });

            $(toolbar).on('click', ".btn-export", function () {
                var options = table.bootstrapTable('getOptions');
                var search = options.queryParams({});
                var filter = search.filter;
                var op = search.op;
                var url = '/NIaBskCwTF.php/centralcontact/export';

                var ids = Table.api.selectedids(table);
                ids = ids.join(",")
                if(ids){
                    url = url+'/ids/'+ids;
                }
                location.href= url + '?filter='+filter+'&op='+op;
            });
        },
        add: function () {
            var pre = Config.isSuperAdmin?"":"tmp_";
            $("#"+pre+"chargedep_ids").val(Config.chargedep_id);

            $("#state").change(function () {
                let state = $(this).val();
                Controller.api.stateChange(state);
            });

            Controller.api.pendingClick();
            Controller.api.bindevent();
            Controller.api.isNewRecord();
        },
        edit: function () {
            Controller.api.pendingInit();
            Controller.api.pendingClick();
            Controller.api.bindevent();
            Controller.api.isNewRecord();

            $("#state").change(function () {
                let state = $(this).val();
                Controller.api.stateChange(state);
            });

            $(".info").click(function(event) {
                var that = this;
                var ids = $(that).data("ids");
                var url ='centralcontact/detail/ids/' + ids +'/is_norecords/1';
                Fast.api.open(url, '', {area:['95%','95%']})
            })
            $(".single_clear").click(function(event) {
                var that = this;
                var item_id = $(that).data("item_id");
                // var data = {};
                // data['item_id'] = item_id;
                Layer.confirm(__('确定要删除当前值吗?'), {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "centralcontact/singledel/ids/"+ item_id,
                        // data: data,
                        success: function (ret) {
                            if(ret.code == 1){
                                Layer.alert(__('删除成功'), function(index){
                                    location.reload();
                                });
                            }else{
                                // Layer.alert();
                                Layer.alert(__(ret.msg), function(index){
                                    parent.location.reload();
                                });

                            }

                        },
                        error : function(error) {
                            console.log(error);
                        }
                    });
                    Layer.close(index);
                });
            });

            $(".single_clear_progress").click(function(event) {
                var that = this;
                var item_id = $(that).data("item_id");
                Layer.confirm(__('确定要删除进展情况吗?'), {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "centralcontact/delprogress/ids/"+ item_id,
                        // data: data,
                        success: function (ret) {
                            if(ret.code == 1){
                                Layer.alert(__('删除成功'), function(index){
                                    location.reload();
                                });
                            }else{
                                Layer.alert(__(ret.msg), function(index){
                                    parent.location.reload();
                                });

                            }

                        },
                        error : function(error) {
                            console.log(error);
                        }
                    });
                    Layer.close(index);
                });
            });

        },
        detail: function (){
            $(".info").click(function(event) {
                var that = this;
                var ids = $(that).data("ids");
                var url ='centralcontact/detail/ids/' + ids ;
                var icon = 'fa fa-info';
                Backend.api.addtabs(url, $(that).data('name'), icon);
            })
        },
        import:function() {
            Controller.api.bindevent();

        },
        leader:function(){
            Table.api.init({
                extend: {
                    index_url: 'centralcontact/leader' + location.search,
                    table: 'centralcontact',
                },
                pageNumber:1,      //初始化加载第一页，默认第一页
                pageSize: 20,      //每页的记录行数（*）
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                showExport:false,
                queryParams:function(params){
                    $.extend(params, {
                        ids: Config.ids
                    });
                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: '', title: __('序号'), table: table,formatter: Table.api.formatter.natureorder, operate: false},

                        {field: 'name', title: __('Name'),width: "100px",operate: 'like'},
                        {field: 'investment_total', title: '总投资(亿)', operate:'BETWEEN',formatter:function(value,row,index) {
                                // console.log(value);
                                if (typeof value == "object" ) {
                                    return '';
                                } else {
                                    return value;
                                }
                            }
                        },

                        {field: 'summary', title: __('项目简介'),operate:false,formatter: function(value,row,index) {
                                var str = value?value:'';
                                return '<div style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+str+'</div>';
                            }},
                        {field: 'progression', title: __('进展情况'),operate:false,formatter: function(value,row,index) {
                                var str = value?value:'';
                                return '<div style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+str+'</div>';
                            }},
                        {field: 'next_measure', title: __('下一步措施'),operate:false,formatter: function(value,row,index) {
                                var str = value?value:'';
                                return '<div style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+str+'</div>';
                            }},
                        {field: 'problem', title: __('存在问题'),operate:false,formatter: function(value,row,index) {
                                var str = value?value:'';
                                return '<div style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+str+'</div>';
                            }},
                        {field: 'access_time_text', title: "计划准入时间",width: "100px",operate:false,},
                        {field: 'sign_time_text', title: __('计划签约时间'),width: "100px",operate:false,},
                        {field: 'investment_area', title: __('投资方地区'),width: "100px"},
                        // {field: 'register_time_text', title: __('注册时间')},
                        {field: 'chargedep_names', title: __('责任单位'),width:'120px',operate: 'like'},
                        {field: 'settle_street_names', title: __('落户街道'),width: "100px",operate: 'like'},
                        {field: 'receive_time',
                        title: __('接洽时间'),
                        width: "100px",
                        addclass:'datetimerange',
                        operate: 'RANGE',
                        formatter: Table.api.formatter.datetimedate},
                        {field: 'leader_names', title: "参与区领导",width: "100px",operate: 'like'},
                        {field: 'centraloffice_name', title: __('责任科室'),width:'120px',operate: 'like'},
                    ]
                ]
            });
            Table.api.bindevent(table);
            var parenttable = table.closest('.bootstrap-table');
            var options = table.bootstrapTable('getOptions');
            var toolbar = $(options.toolbar, parenttable);
            $(toolbar).on('click', ".btn-detail", function () {
                var that = this;
                //循环弹出多个编辑框
                $.each(table.bootstrapTable('getSelections'), function (index, row) {
                    var url = 'centralcontact/detail';
                    row = $.extend({}, row ? row : {}, {ids: row[options.pk]});
                    var url = Table.api.replaceurl(url, row, table);
                    var icon = 'fa fa-info';
                    Backend.api.addtabs(url, '详情-'+row.receive_time_text, icon);
                    // Fast.api.open(url, __('详情'), $(that).data() || {});
                });
            });

            $(toolbar).on('click', ".btn-export", function () {
                var options = table.bootstrapTable('getOptions');
                console.log(options)
                var search = options.queryParams({});
                console.log(search);
                var filter = search.filter;
                var op = search.op;
                // var searchtext = options.searchText;
                var url = '/NIaBskCwTF.php/centralcontact/export/leader_id/'+Config.ids;

                var ids = Table.api.selectedids(table);
                ids = ids.join(",")
                if(ids){
                    url = url+'/ids/'+ids;
                }
                var leader_id = Config.ids;

                url = url + '?filter='+filter+'&op='+op;
                if(options.searchText)
                    url +='&search='+options.searchText;

                 // if(leader_id)
                 //    url +='&leader_id='+leader_id;
                // console.log(url)
                // console.log(filter);
                // console.log(op);
                // console.log(url+ '?filter='+filter+'&op='+op)
                location.href= url;
            });
        },
        checkedit: function(){
            $("#btn-pass").click(function () {
                var ids = $(this).data("ids");
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "centralcontact/checkpass" ,
                    data: {ids:ids},
                    success: function (ret) {
                        Layer.alert(__('提交成功'), function(index){
                            location.reload();
                        });
                    },
                    error : function(error) {
                        console.log(error);
                    }
                });
            });

            $("#btn-reject").click(function () {
                var ids = $(this).data("ids");
                Fast.api.open('centralcontact/checkreject/ids/'+ids, '驳回', {area: ["650px", "300px"]});
            });
            Controller.api.bindevent();
        },
        checkreject: function (){
            $("#btn-reject").click(function () {
                var ids = $(this).data("ids");
                var reject_reason = $("#reject_reason").val();

                Layer.confirm(__('确定要驳回吗?'), {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: "centralcontact/checkreject" ,
                        data: {ids:ids,reject_reason:reject_reason},
                        success: function (ret) {
                            Layer.alert(__('驳回成功'), function(index){
                                parent.location.reload();
                            });
                        },
                        error : function(error) {
                            console.log(error);
                        }
                    });
                    Layer.closeAll();
                });
            });
        },
        addprogress: function (){
            Controller.api.bindevent();
        },
        editprogress:function(){
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            pendingClick: function() {
                $(".pending").click(function() {
                    var item_id = $(this).data('id');
                    var item_type = $(this).data('type') ? $(this).data('type') : 'text';

                    if(item_type == 'text'){
                        if (this.checked) {
                            $("#" + item_id).val("待定");
                            $("#" + item_id).attr('readonly', 'readonly');
                        } else {
                            $("#" + item_id).val("");
                            $("#" + item_id).removeAttr('readonly');
                            $('#' + item_id).prop('disabled',false);
                        }
                    }else if (item_type == 'select'){
                        if (this.checked) {
                            $('#'+item_id).selectpicker('val', '-100');
                            $('#'+item_id).prop('disabled',true);
                            $('#'+item_id).append("<input type='hide' name='"+$("#"+item_id).attr('name')+"' id='hide-"+item_id+"' value='-100' />");
                        } else {
                            $('#'+item_id).selectpicker('val', null);
                            $('#hide-'+item_id).remove();
                            $('#'+item_id).prop('disabled',false);
                        }
                        $('#'+item_id).selectpicker('refresh');
                    }

                })
            },
            pendingInit: function (){
                $(".pending").each(function(){
                    var item_id = $(this).data('id');
                    if($("#"+item_id).val() == '-100' || $("#"+item_id).val() == '待定'){
                        $('#'+item_id).prop('disabled',true);
                        $('#'+item_id).append("<input type='hide' name='"+$("#"+item_id).attr('name')+"' id='hide-"+item_id+"' value='-100' />");
                        $(this).prop("checked",true);
                    }
                });
            },
            isNewRecord: function (){
                $("#record").click(function (){
                    if(this.checked){
                        $("input[name='row[is_new]']").attr('disabled',false);
                    }else{
                        $("input[name='row[is_new]']").attr('disabled',true);
                    }
                });
            },
            stateChange: function(value) {
                var stateArr=[
                    {class_name:'stop_reason_d',value:'终止',input_id:'stop_reason'} ,
                    {class_name:'framework_agreement_d',value: '框架',input_id:'framework_agreement_time'},
                    {class_name:'invesment_agreement_d',value: '正式',input_id:'invesment_agreement_time'},
                    {class_name:'register_d',value: '注册',input_id:'register_time'},
                    {class_name:'start_construction_d',value: '开工',input_id:'start_construction_time'},
                    {class_name:'operation_time_d',value: '运营',input_id:'operation_time'}
               ];
                $(".state_time").hide();

                $.each(stateArr,function (i,val){
                    var id = val.input_id;
                    $("form[role=form]").validator("setField", "row["+id+"]", null);
                    $(".state_time input").removeAttr('aria-invalid');
                });



                let state = stateArr.find(function (item , index) {
                    return item.value == value;
                })

                if(state) {
                    var class_name= state.class_name;
                    var id = state.input_id;
                    $("."+class_name).removeClass('hide');
                    $("."+class_name).show();
                    $("form[role=form]").validator("setField", "row["+id+"]", "required");
                }

            }
        }
    };
    return Controller;
});